import { defineStore } from 'pinia'
import { useUserStore } from './userStore'
import { useWoDetailsStore } from './wodetailsStore'
import { api, API_TSL_FRONTEND } from 'boot/axios'
import { Loading } from 'quasar'

// For QC WO Review Page
export const useWOReviewStore = defineStore('woReview', {
  state: () => ({

    orderNo: null,
    editable: null, // when qc round ended: the wo become readonly 
    allow_reset: null, // QC completed woReview but allowed to reset result
    currentStatus: null, // null: not start, start: started, complete: reviewed
    result: null, // pass / fail -> default: pass
    remark: null, // not required
    flow: null,
    failReason: null,
    checkTime: null, // confirm review result time
    checklist_id: null,

    qcfailReason: [],
    selectedFailReason: []
  }),

  getters: {

    getQCFailReason: (state) => {
      return state.selectedFailReason
    }

  },
  actions: {
    setWOReview () {
      Loading.show()
      // init all values
      const wodetailsStore = useWoDetailsStore()
      // set OrderNo, currentStatus, result, remark, flow, failReason, checkTime, checklist_id, qcfailReason
      this.orderNo = wodetailsStore.orderNo
      this.currentStatus = wodetailsStore.workOrderReview[0].currentStatus
      this.editable = wodetailsStore.workOrderReview[0].editable
      this.result = wodetailsStore.workOrderReview[0].result
      this.allow_reset = wodetailsStore.workOrderReview[0].allow_reset
      this.remark = wodetailsStore.workOrderReview[0].remark
      this.flow = wodetailsStore.workOrderReview[0].flow
      this.failReason = wodetailsStore.workOrderReview[0].failReason
      this.checkTime = wodetailsStore.workOrderReview[0].checkTime
      this.selectedFailReason = wodetailsStore.workOrderReview[0].selectedFailReason
      this.checklist_id = wodetailsStore.workOrderReview[0].checklist_id
      Loading.hide()
    },

    setCurrentStatus (status) {
      // call Start / Complete API
      this.currentStatus = status
      console.log('set CurrentStatus: ', this.currentStatus)
    },

    // Change temp value of result (for woReviewPage) and show on woDetailsPage
    setReviewResult (result) {
      this.result = result
    },

    setFailedReasons (failReason) {
      // do sth qcfailReason
      this.qcfailReason = []

    },

    initReviewResult(){
      this.currentStatus = 'start'
      this.result = null 
      this.remark = null
      this.selectedFailReason = []
    },

    // Start & Complete WO Review
    async qcUpdateWOReview (accID, orderNo, failedDetails, remark, result, action) { 
      const userStore = useUserStore();
      Loading.show()
      // Get current data time
      // const now = new Date()
      // let currentDateTime = now.toISOString()
      // console.log("current DateTime: ", currentDateTime)
      
      // Set Parameters
      let currentDateTime;
      const res = await userStore.pingLogin(); if (res.status === 200) {
        currentDateTime = res.data.date_time;
      } else {
        const now = new Date();
        currentDateTime = now.toISOString();
      }
      let params = null
      if (action === 'start'){
        params = {
          order: orderNo,
          account: accID,
          received_at: currentDateTime
        }
        console.log( 'params: ',params)
      }else if(action === 'complete'){

        let failed_details = []
        if (failedDetails){
          failedDetails.forEach(fd => {
            let temp = {
              reason: fd.id,
              quantity: fd.qty
            }
            failed_details.push(temp)
          })
        }
        
        params = {
          order: orderNo,
          account: accID,
          failed_details: failed_details,
          check_at: currentDateTime,
          failed: result,
          remark: remark
        }
        console.log( 'params: ',params)
      }   

      try{
        // check_record_obj_pk
        const res = await api.put(API_TSL_FRONTEND + '/QCActionView/' + this.checklist_id + '/', params )
        console.log("qcUpdateWOReview res: ",res)
        Loading.hide()
        return true
      }catch (error){
        console.log(error)
        Loading.hide()
        return false
      }
    },

    // Reset WO Review
    async initWOReview (accID, orderNo, failedDetails, remark, action) { 
      Loading.show()
      const userStore = useUserStore();
      let params = null
      // show all parmas:
      console.log('accID: ', accID, ' orderNo: ', orderNo, ' failedDetails: ', failedDetails, ' remark: ', remark, ' action: ', action)
      // Reset
      params = {
        order: orderNo,
        account: accID,
        failed_details: [],
        check_at: null,
        failed: null,
        remark: ""
      }
      // Get current data time
      let currentDateTime;
      const res = await userStore.pingLogin(); if (res.status === 200) {
        currentDateTime = res.data.date_time;
      } else {
        const now = new Date();
        currentDateTime = now.toISOString();
      }
      // const now = new Date()
      // let currentDateTime = now.toISOString()
      console.log("current DateTime: ", currentDateTime)
      try{
        const res = await api.put(API_TSL_FRONTEND + '/QCActionView/' + this.checklist_id + '/reset_qc_result/', params )
        console.log("qcUpdateWOReview res: ",res)
        this.initReviewResult()
        this.editable = true
        Loading.hide()
        return true
      }catch (error){
        console.log(error)
        Loading.hide()
        return false
      }
    }
  }
})


// Sample
// params = {
//   order: '100000354401', // orderNo
//   failed_details: [ // failedDetails
//     {
//       reason: 0,
//       quantity: 2147483647
//     }
//   ],
//   received_at: '2023-06-02T05:26:27.775Z', // When start 
//   check_at: '2023-06-02T05:26:27.775Z', // when finished 
//   failed: true, 
//   remark: 'string', // remark
//   account: 0 // accID
// }
